package com.airlines.crewassignment.service.crew.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.airlines.common.BeanFiledUtils;
import com.airlines.common.TraceUtil;
import com.airlines.crewassignment.domain.Crew;
import com.airlines.crewassignment.domain.drools.CrewRankConvert;
import com.airlines.crewassignment.service.crew.CrewRankConvertService;

/**
 * @author xxxx
 * @date 2018年4月25日 
 * @description
 */
@Service
public class CrewRankConvertServiceImpl implements CrewRankConvertService{
	static Log log = LogFactory.getLog(CrewRankConvertServiceImpl.class);
	@Override
	public void convert(List<Crew> crewList, String fieldName) {
		List<CrewRankConvert> crewRankConvertList =  new ArrayList<>();
		for(Crew crew : crewList){
			int fieldValue = this.getCrewfieldValue(crew, fieldName);
			CrewRankConvert crewRankConvert = new CrewRankConvert();
			crewRankConvert.setWorkcode(crew.getWorkcode());
			crewRankConvert.setRealScore(fieldValue);
			crewRankConvertList.add(crewRankConvert);
		}
		
		this.convertScoreInit(crewRankConvertList);
		
		for(Crew crew : crewList){
			for(CrewRankConvert crc: crewRankConvertList){
				if(StringUtils.equals(crew.getWorkcode(), crc.getWorkcode())){
					this.setCrewfieldValue(crew,fieldName,crc.getConvertScore());
				}
			}
		}
		
	}
	@Override
	public void convertScoreInit(List<CrewRankConvert> crewRankConvertList) {
		int maxRealScore = 0;
		for(CrewRankConvert c : crewRankConvertList){
			maxRealScore = NumberUtils.max(maxRealScore,c.getRealScore(),0);
		}
		
		for(CrewRankConvert c : crewRankConvertList){
			int realScore = c.getRealScore();
			float temp = 0;
			if(maxRealScore != 0){
				temp = (100*realScore) / maxRealScore;
			}
			int convertScore = Math.round(temp);
			c.setConvertScore(convertScore);
		}
		
	}
	
	private void setCrewfieldValue(Crew crew , String fieldName,int convertScore){
		try {
			BeanFiledUtils.forceSetFieldValue(crew.getCrewFlightExperience(), fieldName+"Rank", convertScore);
		} catch (Exception e) {
			log.error("机组人员设置排名得分错误："+TraceUtil.getTrace(e));
		}
	}
	
	private int getCrewfieldValue(Crew crew , String fieldName) {
		Object fieldValue  = null;
		try {
			fieldValue =  BeanFiledUtils.forceGetFieldValue(crew.getCrewFlightExperience(), fieldName);
		} catch (Exception e) {
			log.error("机组人员获取排名得分错误："+TraceUtil.getTrace(e));
		}
		if(fieldValue == null){
			return 0;
		}
		if(NumberUtils.isNumber(fieldValue.toString())){
			return NumberUtils.toInt(fieldValue.toString());
		}
		return 0;
	}
	
	
	
	

}
